package com.tjjingpan.uibestpratise

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import java.lang.IllegalArgumentException

class MsgAdapter(val msgList:List<Msg>): RecyclerView.Adapter<RecyclerView.ViewHolder>() {
    inner class LeftViewHoler(view: View):RecyclerView.ViewHolder(view){
        val leftMsg: TextView = view.findViewById(R.id.leftMsg)
    }
    inner class RightViewHoler(view: View):RecyclerView.ViewHolder(view){
        val rightMsg: TextView = view.findViewById(R.id.rightMsg)
    }

    override fun getItemViewType(position: Int): Int {
       val msg = msgList[position]
        return msg.type
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
    if(viewType == Msg.TYPE_RECEIVED){
        val view = LayoutInflater.from(parent.context).inflate(R.layout.msg_left_item,parent,false)
        LeftViewHoler(view)
    }
    else{
        val view = LayoutInflater.from(parent.context).inflate(R.layout.msg_right_item,parent,false)
       RightViewHoler(view)
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
       val msg = msgList[position]
        when(holder){
            is LeftViewHoler -> holder.leftMsg.text= msg.content
            is RightViewHoler -> holder.rightMsg.text = msg.content
            else -> throw IllegalArgumentException()
        }
    }
    override fun getItemCount(): Int = msgList.size
}